#!/bin/sh
#
# ez-ipupdate     Starts ez-ipupdate
#
RUN_D=/var/run
PID_F=$RUN_D/ez-ipupdate.pid

ddns_dir="/etc/ez-ipupdate"
ddns_cache="$ddns_dir/ez-ipupdate.cache"
ddns_conf="$ddns_dir/ez-ipupdate.conf"
ddns_msg="$ddns_dir/ez-ipupdate.msg"
ddns_exec_ok="$ddns_dir/ez-ipupdate-ok.sh"

getPID(){
    if [ -f $PID_F ]; then 
        echo $(cat $PID_F)
    else 
        echo ""
    fi
}

start() {
        if [ "$(nvram get ddns_enable)" -eq "1" ]; then
         wan_interface=`route | grep default | sed 's/[ ]\{1,\}/ /g' | cut -f8 -d' '`
         #FIRST=0, && FIRST=1
         [ -f $ddns_msg ] || ( mkdir -p $ddns_dir && echo "DynDNS Update started" > $ddns_msg )
         pid=$(getPID)
         if [ -z "$pid" ]; then
            if [ -n "$wan_interface" ]; then
                echo "ez-ipupdate WAN interface: $wan_interface"
                if [ -f $ddns_conf ]; then
                   echo -n "Starting ez-ipupdate:..."
                   /usr/sbin/ez-ipupdate -d -F $PID_F -c $ddns_conf -b $ddns_cache -i $wan_interface -e $ddns_exec_ok
                   #RESULT=`logread | grep 'ez-ipupdate' | grep "$(date +'%b %d %H')" | grep "successful" `
                   #if [ $FIRST -gt 0 -a -z "$RESULT" ]; then
                   # echo "First DynDNS Update was not succesfull" > $ddns_msg
                   # echo "ERROR"
                   #else
                    echo "OK"
                   #fi
                else
                   echo "ez-ipupdate: no configuration file found"
                fi
             else
                echo "ez-ipupdate: no WAN interface found"
             fi
           else
                echo "ez-ipupdate is already running"
           fi
        else
            echo "ez-ipupdate is disabled"
        fi
}

stop() {
        pid=$(getPID)
        if [ -n "$pid" ]; then
            echo -n "Stopping ez-ipupdate:..."
            ( { kill -SIGINT $pid >/dev/null 2>&1
              } && echo "OK" ) || echo "ERROR"
        else
            echo "ez-ipupdate is not running"
        fi
}

restart() {
        stop
        start
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?

